layui.use(['jquery', 'laydate', 'febs', 'form', 'formSelects', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-tenant'),
        $query = $view.find('#query'),
        $add = $view.find('#add'),
        $edit = $view.find('#edit'),
        $delete = $view.find('#delete'),
        $searchForm = $view.find('#tenant-table-form'),
        tableIns;

    form.verify(validate);
    form.render();

    initTable();

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'tenantTable',
            height: getTableHeight(),
            skin: '',
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'tenantName', title: '公司名称', minWidth: 260,style:'color:#01aaed;cursor:pointer',event:'detail'},
                {field: 'shortName', title: '公司简称', minWidth: 60},
                {field: 'tenantCode',align:'center', title: '公司编码', minWidth: 60},
                {field: 'country',align:'center', title: '国家/地区', minWidth: 60},
                {field: 'city',align:'center', title: '所在城市', minWidth: 60},
                {field: 'legalName',align:'center', title: '法人姓名', minWidth: 60},
                {field: 'status',align:'center', title: '状态',templet:'#status',width: 100},
                {field: 'createdBy',align:'center', title: '创建人', width: 140,align:'center'},
                {field: 'createdTime',align:'center', title: '创建时间', width: 140,align:'center'},
                {title: '操作', toolbar: '#tenant-option', width: 160,align:'center'}
            ]],
            toolbar: '#tenantTable-toolbar',
            defaultToolbar: []
        });
        tableIns.reload({url: ctx + 'tenant/list', where: getQueryParams(), page: {curr: 1}});
    }

    // 状态 - 开关操作
    form.on('switch(status)', function(data){
        var status = data.elem.checked;
        var obj = {};
        obj.tenantId = data.value;
        if(!status){
            var title = '确定禁用吗？';
            obj.status = '0';
        }else{
            var title = '重新启用吗？';
            obj.status = '1';
        }
        layer.confirm(title,{icon:3,title:'提示'},function (index) {
            febs.post(ctx + 'tenant/updateStatus', obj, function () {
                $query.trigger('click');
            });
            layer.close(index);
        },function (index) {
            //如果取消了的话，恢复原来的状态
            data.elem.checked = !data.elem.checked;
            form.render('checkbox');
        });
    });

    table.on('toolbar(tenantTable)', function (obj) {
        if (obj.event === 'add') {
            febs.modal.open('新增公司', 'system/tenant/add', {
                btn: ['提交', '取消'],
                area: $(window).width() <= 750 ?  ['95%', '85%']: ['70%', '85%'],
                btn2: function () {
                    layer.closeAll();
                },
                yes: function (index, layero) {
                    $('#tenant-edit').find('#submit').trigger('click');
                },
            });
        }
    });

    //列点击事件
    table.on('tool(tenantTable)', function(obj){
        var data = obj.data; // 获取当前行数据
        var tenantId = data.tenantId;
        if(obj.event === 'detail'){
            febs.modal.open('公司详情', 'system/tenant/detail/'+tenantId, {
                area: $(window).width() <= 750 ?  ['95%', '85%']: ['70%', '85%'],
                btn: ['关闭'],
                shadeClose:true,
                yes: function (index, layero) {
                    layer.closeAll();
                },
            });
        }else if (obj.event === 'edit') {
            febs.modal.open('修改公司', 'system/tenant/update/'+tenantId, {
                btn: ['提交', '取消'],
                area: $(window).width() <= 750 ?  ['95%', '85%']: ['70%', '85%'],
                btn2: function () {
                    layer.closeAll();
                },
                yes: function (index, layero) {
                    $('#tenant-edit').find('#submit').trigger('click');
                },

            });
        } else if (obj.event === 'del') {
            febs.modal.confirm('删除公司', '确定删除所选公司？', function () {
                var tenantIds = [];
                tenantIds.push(tenantId);
                deleteTenants(tenantIds.join(','));
            });
        }
    });

    $query.on('click', function () {
        tableIns.reload({where: getQueryParams(), page: {curr: 1}});
    });

    $edit.on('click', function () {
        var checkStatus = table.checkStatus('tenantTable');
        if (checkStatus.data.length != 1) {
            febs.alert.warn('请选择一条需要修改的数据！');
        } else {
            var id = checkStatus.data[0].tenantId;
            febs.modal.open('修改公司', 'system/tenant/update/'+id, {
                btn: ['提交', '取消'],
                area: $(window).width() <= 750 ?  ['95%', '85%']: ['70%', '85%'],
                btn2: function () {
                    layer.closeAll();
                },
                yes: function (index, layero) {
                    $('#tenant-edit').find('#submit').trigger('click');
                },
            });
        }
    });

    $delete.on('click', function () {
        var checkStatus = table.checkStatus('tenantTable');
        if (!checkStatus.data.length) {
            febs.alert.warn('没有选择要删除的数据！');
        } else {
            febs.modal.confirm('删除公司', '确定删除所选公司？', function () {
                var tenantIds = [];
                layui.each(checkStatus.data, function (key, item) {
                    tenantIds.push(item.tenantId);
                });
                deleteTenants(tenantIds.join(','));
            });
        }
    });

    function getQueryParams() {
        return {
            tenantName: $searchForm.find('input[name="tenantName"]').val()?.trim(),
            shortName: $searchForm.find('input[name="shortName"]').val()?.trim(),
            contact: $searchForm.find('input[name="contact"]').val()?.trim(),
            contactNumber: $searchForm.find('input[name="contactNumber"]').val()?.trim(),
            status:$searchForm.find('select[name="status"]').find('option:selected').val()?.trim(),
            invalidate_ie_cache: new Date()
        };
    }

    function deleteTenants(tenantIds) {
        febs.get(ctx + 'tenant/delete/' + tenantIds, null, function () {
            febs.alert.success('删除公司成功');
            $query.trigger('click');
        })
    }

    function getTableHeight() {
        return commonJS.calcTableHeight(10);
    }

    $(window).resize(function () {
        tableIns.reload({height: getTableHeight()});
    });
});
